package com.maple.utils.widget.timer

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

class MyScheduledExecutor private constructor(): Runnable,DefaultLifecycleObserver {

    private var tick:Long = 0L
    private var isRuning:Boolean = false
    private var job:String = ""
    private var tickListener: TimerTickListener? = null

    private var delayTime: Long = 1L

    fun setDelayTime(time: Long) {
        this.delayTime = time
    }

    private val service by lazy {  Executors.newScheduledThreadPool(4) }

    companion object {
        val INSTANCE: MyScheduledExecutor by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
            MyScheduledExecutor()
        }
    }


    private val initialDelay:Long = 1L
    private val period:Long = 1L

    init {
        service.scheduleAtFixedRate(this,initialDelay,period, TimeUnit.SECONDS)
    }

    fun setListener(listener: TimerTickListener){
        this.tickListener = listener
    }


    fun isRuning():Boolean{
        return isRuning
    }

    fun onReStart(job:String,total:Long){
        if(total <= 0) return
        this.tick = 0L
        this.job = job
        if(!this.isRuning) {
            this.tickListener?.onStart(job)
        }
        this.isRuning = true
    }

    fun onStop(){
        if(this.isRuning) {
            this.tickListener?.onStop(job)
        }
        this.isRuning = false
    }

    fun onDestroy() {
        this.tick = 0L
        this.isRuning = false
        this.tickListener?.onStop(job)
        if(!service.isShutdown) {
            service.shutdownNow()
        }
    }


    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        onReStart("looper", Long.MAX_VALUE)
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        onStop()
    }



    override fun run() {
        this.tick ++
        if(isRuning()){
            val t: Long = tick % delayTime
            if(t == 0L){
                this.tickListener?.onTick(tick)
            }
        }
    }
}